//
//  LocationPolicyManager.m
//  gdemm
//
//  Created by 乔明超 on 16/4/1.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "LocationPolicyManager.h"
#import "ApiSupport.h"
#import "LocationSensor.h"
#import "Location.h"
#import "QRCodeManager.h"
#import "ToastManager.h"
#import "StringUtil.h"
#import "FileUtil.h"
#import "HttpUtil.h"
#import "PolicyManager.h"
#import "WIFIManager.h"
#import <CoreLocation/CoreLocation.h>
@interface LocationPolicyManager()<OnLocationListenerDelegate>
@property (strong,nonatomic) LocationSensor *mSensor; //定位
@property (strong,nonatomic) Location *mLocation; //定位之后返回的位置信息

@property (assign,nonatomic) double mLongtitude;//区域策略文件取出的经度
@property (assign,nonatomic) double mLatitude; //区域策略文件取出的纬度
@property (assign,nonatomic) int mLimitDistance;//区域策略文件取出的经度

@end
@implementation LocationPolicyManager
static LocationPolicyManager *_instance;
- (instancetype)init
{
    self = [super init];
    if (self) {
        _mSensor = [LocationSensor getInstance];
        [_mSensor registerListener:self]; //注册定位的监听者,定位成功之后,传给LocatinPolicyManager的mlocatin
        [_mSensor requestLocationWithMode:LOCATION_TYPE_QRCODE]; //区域策略默认开启模式二维码,并请求定位
        
    }
    return self;
}


+ (instancetype)getInstance{
    if (_instance == nil) {
        @synchronized([self class]) {
            if (_instance == nil) {
                _instance = [[LocationPolicyManager alloc]init];
                
            }
        }
    }
    
    return _instance;
    
}


/*获取连个经纬度之间的距离*/
- (int)getDistanceBy:(double)lon1 :(double)lat1 :(double)lon2 :(double)lat2{
    CLLocation *orinLocation = [[CLLocation alloc]initWithLatitude:lat1 longitude:lon1];
    CLLocation *curLocation = [[CLLocation alloc]initWithLatitude:lat2 longitude:lon2];
    double distace = [curLocation distanceFromLocation:orinLocation];
    return (int)distace;
}



/**
 *  对本地策略中的策略组进行分组保存,区域名.json
 *
 *  @param jstr 策略组JSon数据
 */
- (void)parseJsonToFile:(NSString *)jstr{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths[0] stringByAppendingString:@"/local_config/"];
    if ([StringUtil isEmpty:jstr] || [jstr isEqualToString:@"[]"]) {
        //删除区域策略
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        if ([fileMgr fileExistsAtPath:path]) {
            NSArray *file = [fileMgr contentsOfDirectoryAtPath:path error:nil
             ];
            for (int i = 0; i < file.count; i++) {
                NSString *filePath = [path stringByAppendingString:file[i]];
                [fileMgr removeItemAtPath:filePath error:nil];
            }
        }
        
        return;
    }
    
    NSData *data = [jstr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    //遍历所有的区域策略,并本组保存区域策略信息
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSDictionary *content = (NSDictionary *)obj;
        NSString *keyPath = [path stringByAppendingFormat:@"%@.json",key];
        [content writeToFile:keyPath atomically:YES];
        
    }];
}

/**
 *  扫描到的二维码信息赋值给mQrcode
 *
 *  @param mQrcode 
 */
- (void)setMQrcode:(NSString *)mQrcode{
    
    if ([[QRCodeManager getInstance]isQuitQRcode:mQrcode]) {
        [self closePolicyByQrcode:mQrcode];
        return;
    }
    _mQrcode = mQrcode;
    BOOL isSuccess = [[QRCodeManager getInstance]saveInQrInfo:_mQrcode];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (isSuccess) {
        //[window makeToast:@"扫描二维码区域策略已开启"];
    }else{
        //[window makeToast:@"二维码匹配失败,请重新生成并扫描二维码"];
    }
}

/**
 *  获取存放区域策略文件的路径信息
 *
 *  @return
 */
- (NSString *)getPolicyFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dir = [paths[0] stringByAppendingPathComponent:@"local_config"];
    
    if (![FileUtil mkdirWithPath:dir]) {
        HRLog(@"make policy dir failed %@",dir);
        return nil;
    }
    return [dir stringByAppendingPathComponent:@"locationPolicies.json"];    
}

/**
 *  从二维码中获取分组保存的策略文件的名称
 *
 *  @param name 分组保存的策略文件的名称
 *
 *  @return 策略文件的路径
 */
- (NSString *)getCurrentLocationPolicyByName:(NSString *)name{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dir = [paths[0] stringByAppendingPathComponent:@"local_config"];
    NSString *filePath = [dir stringByAppendingFormat:@"/%@.json",name];
    if (![FileUtil isFileExistWithFilePath:filePath]) {
        [_mSensor requestLocationWithMode:LOCATION_TYPE_WLAN];
        return nil;
    }
    return [dir stringByAppendingFormat:@"/%@",name];
}

/**
 *  下载区域策略文件到本地并按分组保存策略文件
 *
 *  @return 成功返回YES,失败返回NO
 */
- (BOOL)downloadAndParsePolicy{
    NSString *policyUrl =[ApiSupport getLocationPolicyUrl];
    if (policyUrl == nil) {
        
    }else{
        NSString  *tmpPolicyFile = [self getPolicyFile];
        if (tmpPolicyFile != nil ) {
            tmpPolicyFile = [tmpPolicyFile stringByAppendingString:@".tmp"];
            
            if (![HttpUtil downloadPoliciesTofileWithUrl:policyUrl withFileName:tmpPolicyFile]) {
                HRLog(@"download locationPolicy file failed");
            }else{
                NSFileManager *fileMgr = [NSFileManager defaultManager];
                if ([fileMgr fileExistsAtPath:tmpPolicyFile]) {
                    NSString *origin = [self getPolicyFile];
                    [fileMgr removeItemAtPath:origin error:nil];
                    [fileMgr moveItemAtPath:tmpPolicyFile toPath:origin error:nil];
                    NSString *jstr = [FileUtil getFileContent:origin];
                    [self parseJsonToFile:jstr];
                    [fileMgr removeItemAtPath:origin error:nil];
                    
                    return YES;
                }
                
            }
        }
        
    }
    
    return NO;

}

/**
 *  查找区域策略文件是否存在或支持区域策略
 *
 *  @return
 */
- (NSString *)searchLocationPolicyFile{
    QRCodeInfo *qrcode = [[QRCodeManager getInstance]getInQrInfo];
    HRLog(@"qrcode = %@",qrcode);
    if (qrcode != nil && ![StringUtil isEmpty:qrcode.mLocation]) {
        HRLog(@"the  qrcode is :%@",qrcode.mLocation);
        [_mSensor  requestLocationWithMode:LOCATION_TYPE_QRCODE];
    }else if ([self searchLocationPolicyByWlan] == nil){
        [_mSensor requestLocationWithMode:LOCATION_TYPE_GPS];
    }else{
        [_mSensor requestLocationWithMode:LOCATION_TYPE_WLAN];
    
    }
    
    switch (_mSensor.mMode) {
        case LOCATION_TYPE_GPS:
            return [self searchLocationPolicyByGPS];
        case LOCATION_TYPE_WLAN:
            return [self searchLocationPolicyByWlan];
        case LOCATION_TYPE_QRCODE:
            return [self searchLocationPolicyByQRCode];
            
        default:
            return nil;
    }
}

- (NSString *)searchLocationPolicyByQRCode{
    return [self getCurrentLocationPolicyByName:[_mSensor getAddrFromQrcode]];
}

- (NSString *)searchLocationPolicyByWlan{
    HRLog(@"search policy by wlan");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths[0] stringByAppendingString:@"/local_config"];
    
    if ([FileUtil isDirExistAndIsDir:path]) {
        NSArray *fileList = [FileUtil getFileListFromDirectory:path];
        for (int i = 0; i < fileList.count; i++) {
            if ([[fileList[i] lowercaseString]hasSuffix:@"json"]) {
                NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:fileList[i]]];
                NSArray *bindWlanArray = dict[@"bindWlan"];
                NSString *wifiSSID_current = [[WIFIManager getWIFISSID]lowercaseString];
                for (int j = 0; j < bindWlanArray.count; j++) {
                    NSString *wifiSSID_policy = [bindWlanArray[j][@"name"]lowercaseString];
                    if ([wifiSSID_current containsString:wifiSSID_policy]) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIWindow *window = [UIApplication sharedApplication].keyWindow;
                            //[window makeToast:@"WLAN区域策略已开启"];
                        });
                        
                        return [path stringByAppendingPathComponent:fileList[i]];
                    }
                }
                
            }
        }
    }
    [_mSensor requestLocationWithMode:LOCATION_TYPE_GPS];
    return nil;
}

- (NSString *)searchLocationPolicyByGPS{
    HRLog(@"search policy by GPS");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths[0] stringByAppendingString:@"/local_config"];
    if (_mLocation == nil) {
        return nil;
    }
    if ([FileUtil isDirExistAndIsDir:path]) {
        NSArray *fileList = [FileUtil getFileListFromDirectory:path];
        for (int i = 0; i < fileList.count; i++) {
            if ([[fileList[i] lowercaseString]hasSuffix:@"json"]) {
                NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[path stringByAppendingPathComponent:fileList[i]]];
                NSArray *locationArray = dict[@"location"];
                for (int j = 0; j < locationArray.count; j++) {
                    NSString *longitude = locationArray[j][@"longitude"];
                    NSString *latitude = locationArray[j][@"latitude"];
                    _mLimitDistance = [locationArray[j][@"limitDistance"] intValue];
                    
                    /** 默认东经北纬 */
                    BOOL east = YES;
                    BOOL north = YES;
                    /** 获取位置的东经北纬 */
                    unichar we = [longitude characterAtIndex:0];
                    unichar ns = [latitude characterAtIndex:0];
                    if (we == 'W' || we == 'w') {
                        east = NO;
                    }
                    
                    if (ns == 'S' || ns == 's') {
                        north = NO;
                    }
                    
                    /*截取位置的经度和纬度,如经度和纬度没有标明,则不需要截取,默认为东经北纬*/
                    if (we > '9' || we < '0') {
                        _mLongtitude = [[longitude substringFromIndex:1]doubleValue];
                    }else{
                        _mLongtitude = [longitude doubleValue];
                    }
                    
                    if (ns > '9' || ns < '0') {
                        _mLatitude = [[latitude substringFromIndex:1]doubleValue];
                    }else{
                        _mLatitude = [latitude doubleValue];
                    }
                    
                    /*西经为负,南纬为负*/
                    if (!east) {
                        _mLongtitude  = 0.0 - _mLongtitude;
                    }
                    
                    if (!north) {
                        _mLatitude   = 0.0 - _mLatitude;
                    }
                    
                    int distance = [self getDistanceBy:_mLongtitude :_mLatitude :_mLocation.mLongitude :_mLocation.mLatitude];
                    
                    if (distance <= _mLimitDistance) {
                    
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIWindow *window = [UIApplication sharedApplication].keyWindow;
                            //[window makeToast:@"GPS区域策略已开启"];
                        });
                        
                        return [path stringByAppendingPathComponent:fileList[i]];
                    }
                    
                }
                
            }
        }
        [_mSensor requestLocationWithMode:LOCATION_TYPE_QRCODE];
    }
    return nil;
}

- (void)closePolicyByQrcode:(NSString *)qrInfo{
    if ([[QRCodeManager getInstance]quit:qrInfo]) {
        [PolicyManager getInstance].mIsLocalPolicy = NO;
        [[PolicyManager getInstance]clearPolicies];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        //[window makeToast:@"扫描二维码区域策略已关闭"];
        [_mSensor requestLocationWithMode:LOCATION_TYPE_WLAN];
        
    }
}

#pragma mark 实现OnLocationListenerDelegate协议方法
- (void)locationSensor:(LocationSensor *)locationSensor onReceiveLocation:(Location *)location{
    self.mLocation = location;
}
@end
